<template>
  <div class="main">
    <div class="form_content">
      <div class="content">
        <NSpace
          justify="space-between"
          style="margin-bottom: 10rem"
          v-if="props.flat"
        >
          <NSpace>
            <NUpload
              :custom-request="(e: any) => commonUpload(e)"
              multiple
              :show-file-list="false"
            >
              <NButton
                type="primary"
                style="width: 100rem; margin-right: 10rem"
                ghost
              >
                导入
              </NButton>
            </NUpload>
            <NButton
              type="primary"
              style="width: 118rem; margin-right: 10rem"
              @click="downLoad"
              :loading="downLoading"
              ghost
            >
              下载上传模板
            </NButton>
            <NButton
              type="error"
              style="width: 100rem"
              :loading="deleteLoading"
              @click="submit"
              ghost
            >
              删除
            </NButton>
          </NSpace>
          <NButton
            type="primary"
            style="width: 100rem"
            :loading="deleteLoading"
            @click="emits('submit', tableData)"
          >
            确定
          </NButton>
        </NSpace>
        <div class="table">
          <NDataTable
            :bordered="false"
            :columns="columns"
            :data="tableData"
            :pagination="false"
            striped
            :row-key="rowKeys"
            :checked-row-keys="dataListSelections"
            @update:checked-row-keys="selectionChangeHandle"
            max-height="400"
          />
        </div>
      </div>
    </div>
  </div>

  <NModal :auto-focus="false"
    v-model:show="modalVisible"
    @close="modalVisible = false"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="deleteTableDate"
      title="删除提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定删除吗？
      </div>
    </VDialogContent>
  </NModal>
</template>
<script setup lang="ts">
import { NDataTable, useMessage, NButton, NSpace, NModal, NUpload } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import { ref, onMounted, watchEffect } from 'vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { ReceptionModel } from '@/api/reception'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import * as XLSX from 'xlsx'

const message = useMessage()
const props = defineProps(['defaultList', 'flat'])
const emits = defineEmits(['close', 'submit'])

const rowKeys: any = (e: any) => e.idCard || ''
const columns: DataTableColumns = [
  {
    type: 'selection',
    fixed: 'left'
  },
  {
    title: '姓名',
    key: 'name',
    width: 80,
    align: 'center'
  },
  {
    title: '手机号',
    key: 'phone',
    width: 100,
    align: 'center'
  },
  {
    title: '证件类型',
    key: 'idCardType',
    width: 100,
    align: 'center'
  },
  {
    title: '证件号码',
    key: 'idCard',
    width: 50,
    align: 'center'
  },
  {
    title: '职务',
    key: 'duty',
    width: 100,
    align: 'center'
  },
  {
    title: '单位',
    key: 'workUnit',
    width: 50,
    align: 'center'
  }
]
// table的key选择
const dataListSelections: any = ref([])
function selectionChangeHandle(val: any) {
  dataListSelections.value = val
}
// 删除
const deleteLoading = ref(false)
const modalVisible = ref(false)
const submit = async () => {
  if (!dataListSelections.value.length) return message.error('请至少选择一项数据')
  modalVisible.value = true
}
const deleteTableDate = () => {
  deleteLoading.value = true
  dataListSelections.value.map((it: any) => {
    const index = tableData.value.findIndex((c: any) => c.idCard == it)
    if (index !== -1) tableData.value.splice(index, 1)
  })
  deleteLoading.value = false
  modalVisible.value = false
}
// 下载上传模板
const downLoading = ref(false)
const downLoad = async () => {
  downLoading.value = true
  const [error, res, headers] = await sendRequest<HttpResponse<ReceptionModel>>({
    module: 'reception',
    api: 'receptionDownLoad'
  })
  downLoading.value = false
  if (error) return message.error(error.message)
  download(headers, res, '模板')
  message.success('下载模板成功')
}
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
// 导入
const tableData: any = ref([])
const commonUpload = async ({ file, onFinish, onError }: any) => {
  if (!file) return onError()
  if (!file.file.name.includes('xlsx') || !file.file.name.includes('xls')) {
    message.error('请根据模板选择文件')
    return onError()
  }
  const fileReader = new FileReader()
  fileReader.readAsBinaryString(file.file)
  fileReader.onload = (ev: any) => {
    const workbook = XLSX.read(ev.target.result, {
      type: 'binary'
    })
    const wsname = workbook.SheetNames[0]
    const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
    const m = dealExcel(ws)
    tableData.value = [...tableData.value, ...m]
    message.success('导入成功')
    onFinish()
  }
}
// 处理excel数据
const dealExcel = (ws: any) => {
  let keymap: any = ['name', 'phone', 'idCardType', 'idCard', 'duty', 'workUnit']
  ws.forEach((sourceObj: any) => {
    Object.keys(sourceObj).map((keys, index) => {
      sourceObj[keymap[index]] = sourceObj[keys] || null
      delete sourceObj[keys]
    })
  })
  return ws
}

watchEffect(() => {
  if (tableData.value.length || !props.defaultList?.length) return
  tableData.value = props.defaultList
})
onMounted(async () => {})
</script>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 18rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #333333;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .topTitle {
      font-size: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #5fb17f;
      margin-bottom: 10rem;
    }

    .content {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem;
      background-color: #ebeceb;
      @include CommonFont;

      .table {
        width: 60vw;
        height: auto;
      }
    }
  }
}
</style>
